<?php
// -----------------------------------------------------------------------------
// include
// -----------------------------------------------------------------------------
include "../config/config.php";
include "../auth.php";
include "../DBManager.php";
include "../resources/parsedown-1.7.4/Parsedown.php";

// -----------------------------------------------------------------------------
// 数据库相关设置
// -----------------------------------------------------------------------------

$dbPath = "../" . $dbPath; // 不加这行语句的话会报错，提示找不到对应路径
$db = new DBManager("sqlite:" . $dbPath);

// -----------------------------------------------------------------------------

if (!isset($_GET["id"])) {
    exit("需要传入有效的参数！");
}

$id = $_GET["id"];

// -----------------------------------------------------------------------------

/**
 * 传入一个纯文本字符串，返回一个 html 字符串
 * @param string $content
 * @return false|string
 */
function textToHtml(string $content) {

    if (empty(trim($content))) {
        return false;
    } else {

        $str = str_replace(PHP_EOL, "<br />", $content);
        $arr = explode("<br />", $str);
        $result = "";
        $hrMinus = "<hr style='height 1px; border: 0; border-top: 2px dashed gray; margin-top: 4px; margin-bottom: 4px;' />";
        $hrEqual = "<hr style='height 1px; border: 0; border-top: 3px dashed darkorange; margin-top: 4px; margin-bottom: 4px;' />";

        foreach ($arr as $item) {
            if (empty($item) || $item == "\r") {

                $result .= "<br />";

            } elseif ($item == "暂无。") {

                $result .= $item;
                $result .= "<br />";

            } elseif ($item[0] == "=" || $item[0] == "-") {
                // 以 = 或 - 开头

                if (empty(ltrim($item, "="))) {
                    // 全部由 = 组成

                    $item = $hrEqual;
                    $result .= $item;

                } elseif (empty(ltrim($item, "-"))) {
                    // 全部由 - 组成

                    $item = $hrMinus;
                    $result .= $item;

                } else {

                    $result .= <<<BBB
                        <input class="taskItem" type="checkbox" />
                        <span class="taskTitle" role="button">$item</span>
                        <br />
                    BBB;

                }

            } elseif ($item[0] == "#") {
                // 以 # 开头

                $lengthOfItemOld  = strlen($item); // item 字符串的长度，移除左侧 # 符号前的
                $item = ltrim($item, "#"); // 移除左侧的 # 符号
                $lengthOfItemNew = strlen($item); // item 字符串的长度，移除左侧 # 符号后的
                $number = $lengthOfItemOld - $lengthOfItemNew; // 代表着有多少个 # 符号被移除

                if (empty(trim($item))) {
                    // 移除左侧 # 符号后，什么字符都不剩下，或者只剩下了空格

                    $item = "<br />";

                } else {

                    if (empty(trim(str_replace("=", "", $item)))) {
                        // 「# ======」

                        $item = $hrEqual;

                    } elseif (empty(trim(str_replace("-", "", $item)))) {
                        // 「# ------」

                        $item = $hrMinus;

                    } else {

                        if ($number == 1) {

                            $item = "<h5 class='fw-bold'>◆ {$item}</h5>";

                        } else {

                            $item = "<h6 class='fw-bold'>◇ {$item}</h6>";

                        }

                    }

                }

                $result .= $item;


            } else {

                // 判断商品名称中是否包含中文或英文感叹号
                $count = substr_count($item, "!") + substr_count($item, "！");
                if ($count > 0) {
                    if ($count < 3) {
                        $item = "<span class='text-info'>" . $item . "</span>";
                    } else {
                        $item = "<span class='text-danger'>" . $item . "</span>";
                    }
                } else {
                    // 判断商品名称中是否包含中文或英文问号
                    // 如果同时有叹号和问号，不论哪个在前哪个在后，都以叹号为准。
                    $count = substr_count($item, "?") + substr_count($item, "？");
                    if ($count > 0) {
                        $item = "<span class='text-muted fw-lighter'>" . $item . "</span>";
                    } else {
                        $item = "<span class='text-dark'>" . $item . "</span>";
                    }
                }

                $result .= <<<BBB
                <input class="taskItem" type="checkbox" />
                <span class="goodsName" role="button">$item</span>
                <br />
            BBB;

            }
        }
        return $result;

    }

}

// -----------------------------------------------------------------------------

// 设置时区
date_default_timezone_set($region);

// -----------------------------------------------------------------------------
?>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>购物清单</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../resources/bootstrap-5.2.0-beta1-dist/css/bootstrap.min.css">
    <style>
        a {
            text-decoration: none;
        }
        .big {
            font-size: large;
        }
        h5 {
            margin-top: 4px;
            margin-bottom: 4px;
        }
        h6 {
            margin-top: 4px;
            margin-bottom: 4px;
        }
    </style>
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<script src="../resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>
<script src="../resources/jQuery/jquery-3.5.1.js"></script>
<?php include "../globalNavbar.php"; ?>

<!-- ----------------------------------------------------------------------- -->

<div class="container container-fluid mt-3 mb-5">

    <!-- 导航栏 开始 -->
    <div class="mt-3">
        <nav style="--bs-breadcrumb-divider: '>';" aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a class="text-decoration-none" href="<?php echo $homepage; ?>">首页</a></li>
                <li class="breadcrumb-item"><a class="text-decoration-none" href="index.php">购物清单</a></li>
                <li class="breadcrumb-item active">查看</li>
            </ol>
        </nav>
    </div>
    <!-- 导航栏 结束 -->

    <?php

    if (!$db->shoppingListExist($id)) {
        exit("指定的购物清单不存在！");
    }

    $editUrl = "edit.php?id=" . $id;
    $title = "";
    $content = "";

    $arr = $db->readFromShoppingListById($id);
    if (is_array($arr)) {
        $title = $arr["title"];
        $content = $arr["content"];
    }

    echo <<<BBB
        <div class="list-group mb-2">
            <a href="$editUrl" target="_self" class="list-group-item list-group-item-action mb-2">点击编辑(i) - <span class="text-info">{$title}</span></a>
        </div>
    BBB;

    $content = textToHtml($content);
    if ($content) {
        echo <<<BBB
            <div id="content" class="mt-2">
                $content
            </div>
        BBB;
    }

    ?>

</div>

<!-- ----------------------------------------------------------------------- -->

<script src="../resources/jQuery/jquery-3.5.1.js"></script>
<script src="../resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>
<script src="../resources/base64/functions.js"></script>

<!-- ----------------------------------------------------------------------- -->

<script>

    var purchasedGoodsJsonString = ""

    function readFromPurchased(id) {

        var url = "ajax/readFromPurchased.php?id=" + id

        $.get({
            url: url,
            async: false
        })
            .done(function( data ) {
                purchasedGoodsJsonString = data
            })
            .fail(function () {
                alert("请求失败。")
            });

    }

    function writeToPurchased(id, content) {

        var url = "ajax/writeToPurchased.php"

        $.post({
            url: url,
            data: {id: id, content: content},
            async: false
        })
            .done(function () {
                console.log("数据写入成功。")
            })
            .fail(function () {
                alert("请求失败。")
            })

    }

</script>

<!-- ----------------------------------------------------------------------- -->

<script>

    // 点击「待购商品描述文字」时，点击相应的复选框
    $(".goodsName").on("click", function () {
        $(this).prev().click()
    })

    // 点击「待购商品描述文字」前面的「复选框」时执行
    $(".taskItem").change(function () {

        var id = <?php echo $id; ?>;
        readFromPurchased(id)

        var purchasedGoods = []
        if (purchasedGoodsJsonString !== "") {
            // arr string to arr
            purchasedGoodsJsonString = b64_to_utf8(purchasedGoodsJsonString)
            purchasedGoods = JSON.parse(purchasedGoodsJsonString)
        }

        // 取得「待购买商品描述文字」
        var goodsName = $(this).next().text()
        goodsName = goodsName.trim()

        if ($(this).is(':checked')) {
            purchasedGoods.push(goodsName)
            // 数组去重
            purchasedGoods = Array.from(new Set(purchasedGoods))
        } else {
            var index = purchasedGoods.indexOf(goodsName)
            purchasedGoods.splice(index, 1)
        }

        // arr to arr string
        purchasedGoodsJsonString = JSON.stringify(purchasedGoods)
        purchasedGoodsJsonString = utf8_to_b64(purchasedGoodsJsonString)

        var id = <?php echo $id; ?>;
        writeToPurchased(id, purchasedGoodsJsonString)

    })

</script>

<!-- ----------------------------------------------------------------------- -->

<script>

    // 网页加载时执行

    var id = <?php echo $id; ?>;
    readFromPurchased(id)

    if (purchasedGoodsJsonString !== "") {

        // arr string to arr
        purchasedGoodsJsonString = b64_to_utf8(purchasedGoodsJsonString)
        var purchasedGoods = JSON.parse(purchasedGoodsJsonString)

        if (purchasedGoods.length !== 0) {
            var arr = $(".taskItem")

            for (var item of arr) {
                var goodsName = $(item).next().text().trim()
                for (var f in purchasedGoods) {
                    if (purchasedGoods[f] == goodsName) {
                        $(item).attr("checked", true)
                    }
                }
            }
        }

    }

</script>

<!-- ----------------------------------------------------------------------- -->

<!-- 添加「返回顶部按钮」 -->
<script src="../resources/vanilla-back-to-top/index.js"></script>
<script src="../resources/vanilla-back-to-top/config.js"></script>

<!-- ----------------------------------------------------------------------- -->

<script>

    // 快捷键
    var keyGPressed = 0;
    $(window).keydown(function(event){

        switch (event.key) {
            case "i":
                // 进入编辑
                keyGPressed = 0;
                var url = "<?php echo $editUrl; ?>";
                window.open(url, "_self");
                break
            case "g":
                // 返回顶部
                if (keyGPressed == 1) {
                    $("html, body").animate({ scrollTop: 0});
                    keyGPressed = 0
                } else {
                    keyGPressed = 1
                }
                break
            case "j":
                keyGPressed = 0;
                // 屏幕向下滚动一小段距离
                var y = $(window).scrollTop();
                $('html, body').animate({ scrollTop: y + 650})
                break;
            case "k":
                keyGPressed = 0;
                // 屏幕向上滚动一小段距离
                var y = $(window).scrollTop();
                $('html, body').animate({ scrollTop: y - 650})
                break;
            default:
                keyGPressed = 0;
                break;
        }

        // 滚动到屏幕底部
        if (event.shiftKey) {
            switch (event.key) {
                case 'G':
                    keyGPressed = 0;
                    $("html, body").animate({ scrollTop: $(document).height() }, 1000);
                    break
            }
        }

    })

</script>

<!-- ----------------------------------------------------------------------- -->

</body>
</html>
